<?php

namespace App\Kuafu\User\Service;

use App\Kuafu\Base\Enum\BaseCodeEnum;
use App\Kuafu\Base\Service\BaseService;
use App\Kuafu\Common\Enum\CodeEnum;
use App\Kuafu\Shop\Model\ShopRecordsModel;
use App\Kuafu\User\Enum\RoleCodeEnum;
use App\Kuafu\User\Enum\UserCodeEnum;
use App\Kuafu\User\Exceptions\UserException;
use App\Kuafu\User\Exceptions\UserRoleException;
use App\Kuafu\User\Model\Role;
use App\Kuafu\User\Model\UserRoleMapping;
use App\Kuafu\User\Validate\UserRoleValidate;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Artisan;
use Illuminate\Support\Facades\DB;

class UserRoleService extends BaseService
{
    public static function getUserRole(Request $request)
    {
        $brandId = $request->post('brandId', 0);
        $shopId  = $request->post('shopId', 0);
        $userId  = $request->post('userId', 0);

        // 校验
        $valid = UserRoleValidate::getUserRole($request);
        if ($valid) {
            return self::returnData(UserCodeEnum::ERR_PMS_NOT_INPUT, $valid);
        }

        $query = UserRoleMapping::getDataFirst($userId, $brandId, $shopId);

        if (!$query || !$query->roleRel) {
            return self::returnData(BaseCodeEnum::OK, '', []);
        }

        return self::returnData(BaseCodeEnum::OK, '', [
            'userRoleId' => $query->id,
            'roleId'     => $query->roleId,
            'roleName'   => $query->roleRel->name
        ]);
    }

    public static function getUserRoleMapping($userId, $brandId, $shopId)
    {
        return UserRoleMapping::getDataFirst($userId, $brandId, $shopId);
    }

    /**
     * 获取根据用户 Id 获取用户品牌列表
     *
     * @param int $user
     * @return array
     */
    public static function getUserBrandIdList(int $user): array
    {
        $urm = new UserRoleMapping();

        $list = $urm::query()->where("userId", $user)
                    ->where("shopId", 0)
                    ->get(['brandId'])
                    ->toArray();

        return $list;
    }

    /**
     * 根据平台类型,用户 ID 获取关联角色的品牌 Id
     *
     * @param int $userId
     * @param int $platform
     */
    public static function getUserBrandIdListByMapping(int $userId, int $platform)
    {
        $urm = new UserRoleMapping();

        $list = $urm::query()->where("userId", $userId)
                    ->where("shopId", 0)
                    ->get(['brandId'])
                    ->toArray();

        return $list;
    }

    /**
     * 获取根据用户 Id 获取用户品牌列表
     *
     * @param int $user
     * @param int $brandId
     * @return array
     */
    public static function getUserShopIdsList(int $user, int $brandId = 0): array
    {
        $urm = new UserRoleMapping();

        $list = $urm::query();

        if ($brandId) {
            $list = $list->where('brandId', $brandId);
        }

        $list = $list
            ->where("userId", $user)
            ->where('shopId', '<>', 0)
            ->get(['shopId'])
            ->toArray();

        return $list;
    }

    /**
     * 批量添加数据
     *
     * @param $userId
     * @param $roleList
     */
    public static function addUserRoleData($userId, $roleList, $outBrandId = 0)
    {
        try {
            $currentUid = AuthService::getUserId();
        } catch (\Exception $e) {
            $currentUid = 0;
        }

        $shopInsertList  = [];
        $brandInsertList = [];
        // 新增web品牌角色
        if (!empty($roleList['brandRoles'])) {
            foreach ($roleList['brandRoles'] as $brandValue) {
                $brandInsertList[] = [
                    'userId'       => $userId,
                    'roleId'       => $brandValue,
                    'brandId'      => $outBrandId,
                    'shopId'       => 0,
                    'type'         => RoleCodeEnum::ROLE_WEB_TYPE,
                    'createdAt'    => time(),
                    'updatedAt'    => time(),
                    'createdByUid' => $currentUid,
                    'updatedByUid' => $currentUid,
                ];
            }
        }

        // 新增pos门店角色
        if (!empty($roleList['shopRoles'])) {
            foreach ($roleList['shopRoles'] as $shopId => $shopValue) {
                foreach ($shopValue as $svValue) {
                    $shopInsertList[] = [
                        'userId'       => $userId,
                        'roleId'       => $svValue,
                        'brandId'      => $outBrandId,
                        'shopId'       => $shopId,
                        'type'         => RoleCodeEnum::ROLE_POS_TYPE,
                        'createdAt'    => time(),
                        'updatedAt'    => time(),
                        'createdByUid' => $currentUid,
                        'updatedByUid' => $currentUid,
                    ];
                }
            }
        }
        //新增商家app角色
        if (!empty($roleList['merchantRoles'])) {
            $tempShopIds = [];
            foreach ($roleList['merchantRoles'] as $shopId => $shopValue) {
                foreach ($shopValue as $svValue) {
                    $tempShopIds[] = $shopId;
                    $shopInsertList[] = [
                        'userId'       => $userId,
                        'roleId'       => $svValue,
                        'brandId'      => $outBrandId,
                        'shopId'       => $shopId,
                        'type'         => RoleCodeEnum::ROLE_BUSINESS_TYPE,
                        'createdAt'    => time(),
                        'updatedAt'    => time(),
                        'createdByUid' => $currentUid,
                        'updatedByUid' => $currentUid,
                    ];
                }
            }
            // 同步员工档案
            try {
                // 获取未建档的门店Id
                $existShopIds = ShopRecordsModel::query()
                    ->whereIn('shopId', $tempShopIds)
                    ->pluck('shopId')
                    ->toArray();

                $addShopIds = array_diff($tempShopIds, $existShopIds);
                if (!empty($addShopIds)) {
                    Artisan::call('shop:init_shop_and_shop_staff_records --shopIds=' . join(',', $addShopIds));
                }
                Artisan::call('shop:refresh_shop_staff_statistics --userIds=' . $userId);
            } catch (\Exception $exception) {}
        }

        $insertData = array_merge($brandInsertList, $shopInsertList);
        UserRoleMapping::batchAddUserRoleMapping($insertData);
    }

    /**
     * 删除用户角色信息
     *
     * @param $userId
     */
    public static function deleteRoleData($userId)
    {
        UserRoleMapping::query()->where('userId', $userId)->withoutGlobalScope('isDel')->delete();
    }


    /**
     * 获取 WEB 当前用户的角色列表
     *
     * @param int $userId
     * @param int $shopId
     * @param int $brandId
     * @return array
     * @throws UserRoleException
     */
    public static function getWebUserRoleList(int $userId, int $brandId, int $shopId = 0)
    {
        $result = UserRoleMapping::getUserRoleList($userId, $brandId, $shopId, RoleCodeEnum::ROLE_WEB_TYPE);

        if ($result->isEmpty()) {
            return [];
        } else {
            return $result->pluck('roleId')->toArray();
        }
    }




    /*****以下接口区分平台******/

    /**
     * [区分平台]通过品牌 Id / 店铺 Id获取当前用户的角色 Id
     *
     * @param int $userId
     * @param int $shopId
     * @param int $brandId
     * @param int $platform 0 b
     * @return int
     * @throws UserRoleException
     */
    public static function getUserRoleId(
        int $userId,
        int $shopId,
        int $brandId,
        int $platform = CodeEnum::PLATFORM_B_BRAND
    ): int {
        if (empty($shopId)) {
            return UserRoleMapping::getUserRoleIdByBrandId($userId, $brandId, $platform);
        } else {
            return UserRoleMapping::getUserRoleByShopId($userId, $shopId, $platform);
        }
    }

    /**
     * @param $userId
     * @param $shopId
     * @param $positions
     * @param $brand
     * @param Collection $roles
     * @throws UserException
     */
    public static function addUserRoleMapData($userId, $shopId, $positions, $brand, $roles, int $induction, int $inShop)
    {
        DB::beginTransaction();
        try {
            foreach ($positions as $v) {
                UserRoleMapping::addUserRoleMap($userId, $shopId, $v, $brand,
                    $roles->where("id", "=", $v)->first()->type, $induction, $inShop);
            }
            DB::commit();
        } catch (\Exception $exception) {
            DB::rollback();
            throw new UserException(UserCodeEnum::ERR_USER_INSERT, '', $exception);
        }
    }

    public static function setIsDelStaffData(
        $userId,
        $shopId,
        $delUserRole,
        $brand,
        $updated
    ) {
        try {
            UserRoleMapping::setIsDelStaff($userId, $shopId, $delUserRole, $brand, $updated);
        } catch (\Exception $exception) {
            throw new UserException(UserCodeEnum::ERR_USER_UPDATE, '', $exception);
        }
    }
//
//    public static function checkPermission(
//        int $userId,
//        int $shopId,
//        int $brandId,
//        int $platform = CodeEnum::PLATFORM_B_BRAND)
//    {
//
//        // 用户名下全部的
//        $roleMapping = Cache::remember(UserCacheEnum::getUserRoles($userId), 5,
//            function () use ($brandId, $shopId, $userId) {
//                return UserRoleMapping::query()
//                                      ->where('userId', $userId)
//                                      ->get();
//            });
//
//        $roleIds = $roleMapping->where('shopId', $shopId)->when($brandId, function($query) use ($brandId) {
//            return $query->where('brandId', $brandId);
//        })->pluck('roleId');
//    }

    /**
     * 检查店铺是否有某个角色
     * @param int $shopId
     * @param int $roleId
     * @param int $type
     * @param int $userId
     * @return array|Builder[]|Collection|\Illuminate\Support\Traits\Conditionable[]
     */
    public static function checkRoleInShop(int $shopId, int $roleId, int $type, int $userId = 0)
    {
        return UserRoleMapping::query()
                              ->with([
                                  'userRel' => function ($query) {
                                      $query->where('status', \App\Kuafu\User\Enum\CodeEnum::USER_STATUS_USE);
                                  }
                              ])
                              ->where('shopId', $shopId)
                              ->where('roleId', $roleId)
                              ->where('type', $type)
                              ->when($userId, function ($query) use ($userId) {
                                  $query->where('userId', $userId);
                              })
                              ->get()
                              ->filter(function ($item) {
                                  if ($item->userRel) {
                                      return true;
                                  }

                                  return false;
                              })
                              ->values();
    }

    /**
     * @param int $roleId
     * @return Builder[]|Collection
     */
    public static function roleUserLists(int $roleId)
    {
        return [
            "userLists" => UserRoleMapping::query()
                                          ->with([
                                              'userRel' => function ($query) {
                                                  $query->where('status',
                                                      \App\Kuafu\User\Enum\CodeEnum::USER_STATUS_USE);
                                              }
                                          ])
                                          ->where('roleId', $roleId)
                                          ->get()
                                          ->filter(function ($item) {
                                              if ($item->userRel) {
                                                  return true;
                                              }
                                              return false;
                                          }
                                          )->map(function ($v) {
                    return $v->userRel;
                })
                                          ->values()->toArray()
        ];
    }

    /**
     * @param int $roleId
     * @return Builder[]|Collection
     */
    public static function roleUserListsByShopAreaCode(int $roleId)
    {


        return [
            "userLists" => UserRoleMapping::query()
                                          ->with([
                                              'userRel' => function ($query) {
                                                  $query->where('status',
                                                      \App\Kuafu\User\Enum\CodeEnum::USER_STATUS_USE);
                                              }
                                          ])
                                          ->where('roleId', $roleId)
                                          ->get()
                                          ->filter(function ($item) {
                                              if ($item->userRel) {
                                                  return true;
                                              }
                                              return false;
                                          }
                                          )->map(function ($v) {
                    return $v->userRel;
                })
                                          ->values()->toArray()
        ];
    }

    /**
     * @param int $roleId
     * @param array $shopIds
     * @return Builder[]
     */
    public static function getShopManageList(int $roleId, array $shopIds, int $filterWebUser = 0): array
    {
        // 需要过滤掉的用户ids
        if ($filterWebUser) {
            $filterUserIds = UserRoleMapping::getWebUserIds();
        } else {
            $filterUserIds = [];
        }

        return [
            "lists" => UserRoleMapping::query()
                ->whereIn('shopId', $shopIds)
                ->with(['userRel' => function ($query) {
                    $query->where('status', \App\Kuafu\User\Enum\CodeEnum::USER_STATUS_USE);
                }])
                ->where('roleId', $roleId)
                ->get()
                ->filter(function ($item) use ($filterUserIds) {
                    if (!$item->userRel) {
                        return false;
                    }

                    if (in_array($item->userId, $filterUserIds)) {
                        return false;
                    }

                    return true;
                })
                ->map(function ($v) {
                    return [
                        'userId'       => $v->userRel->id,
                        'shopId'       => $v->shopId,
                        'username'     => $v->userRel->username,
                        'mobile'       => $v->userRel->mobile,
                        'feishuUserId' => $v->userRel->feishuUserId,
                    ];
                })->values()->toArray()
        ];
    }

    /**
     * @param int $userId
     * @param int $roleId
     * @return array
     */
    public static function getShopIdsByUserManager(int $userId, int $roleId): array
    {
        return UserRoleMapping::query()
                              ->where('userId', $userId)
                              ->where('roleId', $roleId)
                              ->pluck('shopId')
                              ->toArray();
    }

    /**
     * @param int $roleId
     * @param int $userId
     * @return bool[]
     */
    public static function isRoleUser(int $roleId, int $userId): array
    {
        return [
            "isRoleUser" => (bool)UserRoleMapping::query()->where("roleId", $roleId)
                                                 ->where("userId", $userId)
                                                 ->first()
        ];
    }
}
